﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using MS.InformationManagement.Presenter.Support;
using MS.InformationManagement.Presenter.ListUploaders;
using MS.InformationManagement.Support;

namespace MS.InformationManagement.WP.RecordCenter.BackdropMassUploader
{
    public partial class BackdropMassUploaderUserControl : BaseControl, IListUploaderView
    {
        #region [Private Fields]

        private ListUploaderPresenter _Presenter;

        #endregion

        #region [Event Handlers]

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            _Presenter = new ListUploaderPresenter(this);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                switch (Operation)
                {
                    case Support.Enums.ListUploadOperation.Backdrop:
                        hplTemplate.NavigateUrl = Page.ResolveUrl("~/_layouts/inc/MS.InformationManagement/templates/fondos.csv");
                        break;
                    case Support.Enums.ListUploadOperation.Sections:
                        hplTemplate.NavigateUrl = Page.ResolveUrl("~/_layouts/inc/MS.InformationManagement/templates/secciones.csv");
                        break;
                    case Support.Enums.ListUploadOperation.Series:
                        hplTemplate.NavigateUrl = Page.ResolveUrl("~/_layouts/inc/MS.InformationManagement/templates/series.csv");
                        break;
                    case Support.Enums.ListUploadOperation.Subseries:
                        hplTemplate.NavigateUrl = Page.ResolveUrl("~/_layouts/inc/MS.InformationManagement/templates/subseries.csv");
                        break;
                    case Support.Enums.ListUploadOperation.Entities:
                        hplTemplate.NavigateUrl = Page.ResolveUrl("~/_layouts/inc/MS.InformationManagement/templates/entidades.csv");
                        break;
                    case Support.Enums.ListUploadOperation.People:
                        hplTemplate.NavigateUrl = Page.ResolveUrl("~/_layouts/inc/MS.InformationManagement/templates/personas.csv");
                        break;
                    default: break;
                }
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            warningmessagecontainer.Visible = false;
            try
            {
                if (fileBackdrop.PostedFile == null || fileBackdrop.PostedFile.ContentLength == 0)
                {
                    HandleWarning("Debe seleccionar un archivo antes de realizar el proceso de carga.");
                    return;
                }
                if (!CheckFileExtension()) {
                    HandleWarning("El archivo que intenta cargar no es un archivo separado por comas [,] (.csv). Verifique el archivo e inténtelo de nuevo.");
                    return;
                }
                _Presenter.UploadeFile();

            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            string isDlg = Request.QueryString.Get("IsDlg");
            if (!string.IsNullOrEmpty(isDlg) && isDlg.Equals("1")) { this.CloseWindow(); }
            else { this.GoCurrentUserHome(); }
        }

        #endregion

        #region [IListUploaderMembers]

        public System.IO.Stream FileStream
        {
            get { return fileBackdrop.PostedFile.InputStream; }
        }

        public Support.Enums.ListUploadOperation Operation
        {
            get { return ViewState["Operation"] == null ? Support.Enums.ListUploadOperation.None : (Support.Enums.ListUploadOperation)ViewState["Operation"]; }
            set { ViewState["Operation"] = value; }
        }

        public void ShowSuccess(string message)
        {
            HandleSuccess("Proceso terminado", new WebControl[] { }, false);
            warningmessagecontainer.InnerHtml = string.Format("<b>Advertencia: se encontraron los siguientes conflictos al intentar cargar el archivo:</b> <br/><p class='warnings'>{0}</p>", message);
            warningmessagecontainer.Visible = true;
        }
        
        public void ShowSuccess()
        {
            HandleSuccess("El archivo ha sido cargado exitosamente", new WebControl[] { btnUpload, btnCancel }, true);
        }

        public bool CheckFileExtension()
        {
            int startingIndex = fileBackdrop.PostedFile.FileName.LastIndexOf('.')+1;
            string fileExtension = fileBackdrop.PostedFile.FileName.Substring(startingIndex);
            return fileExtension.ToLower().Equals("csv");
        }

        #endregion
    }
}
